﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Ortodoctor.gridComponent
{
    public class Grid
    {
        public DataTable dados { get; set; }
        public int page { get; set; }
        public int total { get; set; }
        public string columnId { get; set; }

        public Grid()
        {
            dados = new DataTable();
            page = 0;
            total = 0;
            columnId = "";
        }

        public Grid(DataTable dt, string columnId)
        {
            dados = dt.Copy();
            page = 1;
            total = dados.Rows.Count;
            this.columnId = columnId;
        }

        public string getDadosToJson(DataTable paginaAtual)
        {
            string retorno = "{page:" + page + ",total:" + total + ",rows:[";
            string linhas = "";
            foreach (DataRow dr in paginaAtual.Rows)
            {
                if(!string.IsNullOrEmpty(linhas))
                    linhas += ",";
                linhas += "{id:'" + dr[columnId] + "', cell:{";
                string colunas = "";
                foreach (DataColumn dc in paginaAtual.Columns)
                {
                    if (!string.IsNullOrEmpty(colunas))
                        colunas += ",";
                    colunas += dc.ColumnName + ":'" + dr[dc.ColumnName] + "'";
                }
                linhas += colunas + "}}";
            }
            return retorno + linhas + "],post:[]}";
        }

        public void editTable(int id, string[] valores)
        {
            if (id >= 0)
            {
                DataRow[] dr = dados.Select(columnId + "=" + id);
                if (dr.Length > 0)
                {
                    int i = 0;
                    foreach (DataColumn dc in dados.Columns)
                    {
                        if (!dc.ColumnName.Equals(columnId))
                            dr[0][dc.ColumnName] = valores[i++];
                    }
                }
            }
        }

        public void deleteFromTable(int id)
        {
            if (total > 0)
            {
                DataRow[] dr = dados.Select(columnId + "=" + id);
                if (dr.Length > 0)
                {
                    dados.Rows.Remove(dr[0]);
                    --total;
                }
            }
        }
    }
}